using System.Data;
using Microsoft.Extensions.Options;
using SPI.AgentServer.Configuration;
using SPI.AgentServer.Services.Execution;

namespace SPI.AgentServer.Services.Tools;

/// <summary>
/// 告警查询工具 - 查询最近的告警记录
/// </summary>
public class GetRecentAlarmsTool : IQueryTool
{
    private readonly IDatabaseExecutor _executor;
    private readonly DatabaseConfiguration _config;
    private readonly ILogger<GetRecentAlarmsTool> _logger;

    public string Name => "get_recent_alarms";
    public string Description => "查询最近的告警记录，支持按时间范围、告警级别、区域等条件筛选";

    public GetRecentAlarmsTool(
        IDatabaseExecutor executor,
        IOptions<DatabaseConfiguration> options,
        ILogger<GetRecentAlarmsTool> logger)
    {
        _executor = executor;
        _config = options.Value;
        _logger = logger;
    }

    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (!ValidateParameters(parameters, out var errors))
        {
            return new ToolResult
            {
                Success = false,
                Errors = errors
            };
        }

        try
        {
            // 获取参数，设置默认值
            var limit = parameters.ContainsKey("limit")
                ? Convert.ToInt32(parameters["limit"])
                : 10;

            // alarmLevel 参数：只有当是有效整数时才使用
            int? alarmLevel = null;
            if (parameters.ContainsKey("alarmLevel"))
            {
                var levelStr = parameters["alarmLevel"]?.ToString();
                if (!string.IsNullOrEmpty(levelStr) &&
                    !levelStr.Equals("所有", StringComparison.OrdinalIgnoreCase) &&
                    !levelStr.Equals("all", StringComparison.OrdinalIgnoreCase) &&
                    int.TryParse(levelStr, out var level))
                {
                    alarmLevel = level;
                }
            }

            var areaId = parameters.ContainsKey("areaId")
                ? parameters["areaId"]?.ToString()
                : null;

            var startTime = parameters.ContainsKey("startTime")
                ? parameters["startTime"]?.ToString()
                : null;

            var endTime = parameters.ContainsKey("endTime")
                ? parameters["endTime"]?.ToString()
                : null;

            // operateStatus 参数：只有当是有效整数时才使用
            int? operateStatus = null;
            if (parameters.ContainsKey("operateStatus"))
            {
                var statusStr = parameters["operateStatus"]?.ToString();
                if (!string.IsNullOrEmpty(statusStr) &&
                    !statusStr.Equals("所有", StringComparison.OrdinalIgnoreCase) &&
                    !statusStr.Equals("all", StringComparison.OrdinalIgnoreCase) &&
                    int.TryParse(statusStr, out var status))
                {
                    operateStatus = status;
                }
            }

            // 构建 SQL 查询（使用 MySQL LIMIT 语法）
            var sql = @"
SELECT
    Id,
    EventType,
    Name,
    AlarmName,
    AlarmLevel,
    OperateStatus,
    IsConfirm,
    AlarmCreateTime,
    AlarmHandleEndTime,
    WhoHandled,
    AlarmHandleRemark,
    DeviceId,
    AreaId,
    StationAreaId
FROM tblalarmlog
WHERE IsValid = 1";

            // 添加筛选条件
            if (alarmLevel.HasValue)
            {
                sql += $" AND AlarmLevel = {alarmLevel.Value}";
            }

            if (!string.IsNullOrEmpty(areaId))
            {
                sql += $" AND (AreaId = '{areaId}' OR StationAreaId = '{areaId}')";
            }

            if (!string.IsNullOrEmpty(startTime))
            {
                sql += $" AND AlarmCreateTime >= '{startTime}'";
            }

            if (!string.IsNullOrEmpty(endTime))
            {
                sql += $" AND AlarmCreateTime <= '{endTime}'";
            }

            if (operateStatus.HasValue)
            {
                sql += $" AND OperateStatus = {operateStatus.Value}";
            }

            sql += " ORDER BY AlarmCreateTime DESC";
            sql += $" LIMIT {limit}";  // 使用 MySQL 的 LIMIT 语法

            _logger.LogInformation("Executing recent alarms query: {Sql}", sql);

            var result = await _executor.ExecuteQueryAsync(sql, null, cancellationToken);

            return new ToolResult
            {
                Success = true,
                Data = result.Data,
                Message = $"查询到 {result.RowCount} 条告警记录",
                Metadata = new Dictionary<string, object>
                {
                    ["rowCount"] = result.RowCount,
                    ["executionTimeMs"] = result.ExecutionTimeMs,
                    ["executedSql"] = sql
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing recent alarms query");
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { $"查询错误: {ex.Message}" }
            };
        }
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();

        // 验证 limit 参数
        if (parameters.ContainsKey("limit"))
        {
            if (!int.TryParse(parameters["limit"]?.ToString(), out var limit) || limit <= 0 || limit > 1000)
            {
                errors.Add("参数 'limit' 必须是 1-1000 之间的整数");
            }
        }

        // alarmLevel 参数可选，允许为空字符串或"所有"等描述性文字
        // 不再强制要求必须是整数

        return errors.Count == 0;
    }
}
